<?php
namespace app\agent\service;

use app\agent\logic\UserTginfoLogic;
use app\agent\servlet\UserTginfoServlet;

class UserTginfoService extends BaseService
{
	private $userTginfo = null;
	
	private $servlet = null;
	
	public function __construct()
	{
		parent::__construct();
		
		$this->userTginfo = new UserTginfoLogic();
		
		
		$this->servlet = new UserTginfoServlet();
		
	}
	
	public function getViewPage($request = [])
	{
        $request = $this->servlet->collating($request);

		$where = $this->servlet->getWhere($request);
		
		$data = $this->userTginfo->getPage($where, $request);

		//获取今日新增经纪人
        $dayInfo = $this->userTginfo->dayTginfo($where);

		$data = [
				'data' => $data,
				'dayInfo' => $dayInfo,
				'status' => $this->userTginfo->_map['status'],
		];
		
		return $data;
	}

	/**
	* @action 辖区经纪人详情
	*/
	public function getViewDetail($data = [])
	{
		$where = [
				$this->userTginfo->getPk() => $data['id'],
		];

		$data = $this->userTginfo->getDetail($where);

		//获取商家数量
        $where = [
            ['bind_uid', '=', $data['uid']],
        ];

        $data['seller_count'] = db('wk_seller')->where($where)->count(1);

		if ( $data === false )
		{
			$this->error = $this->userTginfo->getError();

			return false;
		}
		
		return $data;
	}
    /**
     * 经纪人审核通过
     * @param array $data
     * @return bool
     */
    public function changeStatus($data = [])
    {
        //整理数据
        $data   = $this->servlet->collating($data);
        $data['oktime'] = time();

        //入库
        $res = $this->userTginfo->allowField(true)->save($data, ['id' => $data['id']]);

        if( $res === false )
        {
            $this->error = '操作失败!';

            return false;
        }

        //更改user表
        $tginfo = $this->userTginfo->find($data['id']);

        $where = [
            ['uid', '=', $tginfo->uid]
        ];

        $datas = [
            'istuiguang'   => $tginfo->tgnumber,
            'bindtuiguang' => $tginfo->bdtguid,
            'updatetime'   => time(),
        ];

        db('user')->where($where)->update($datas);

        //修改结构链和上级的count
        user_tginfo_add($tginfo['uid']);

        return true;
    }
}